package com.smartwebx.fr.util;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import com.google.common.base.Function;
import com.google.common.collect.Lists;

/**
 * 处理集合数据
 * 
 * @author XX
 * 
 */
public class TableDataConver {
	private List<List<String>> tableData;

	private TableDataConver(List<List<String>> table) {
		this.tableData = table;
	}

	public static TableDataConver getInstance(List<List<String>> table) {
		return new TableDataConver(table);
	}

	/**
	 * 根据列索引获得当列数据，日期类型
	 * 
	 * @param y
	 * @param dateFormat
	 * @return
	 * @throws ParseException
	 * @throws StoredProcException
	 */
	public List<String> getYListByTableAsY_Date(int index,
			final String dateFormat) {
		List<Date> datesByIndex = getDateListByY(index, dateFormat);

		return Lists.transform(datesByIndex, new Function<Date, String>() {
			@Override
			public String apply(Date input) {
				return DateFormatUtils.format(input, dateFormat);
			}
		});
	}

	/**
	 * 获得当列数据（日期）根据列索引
	 * 
	 * @param yIndex
	 * @param dateFormat
	 * @return
	 * @throws StoredProcException
	 * @throws ParseException
	 */
	private List<Date> getDateListByY(int yIndex, String dateFormat) {

		List<Date> yList = new ArrayList<Date>();
		for (int i = 0; i < tableData.size(); i++) {
			List<String> line = tableData.get(i);
			if (line.size() > yIndex) {
				String point = line.get(yIndex);
				try {
					Date d = DateUtils.parseDate(point, "yyyy-MM-dd",
							"yyyy-MM-dd HH:mm", "HH:mm");
					yList.add(d);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return yList;
	}

	/**
	 * 获得Double类型的列数据
	 * 
	 * @param y
	 * @return
	 * @throws StoredProcException
	 */
	public List<Double> getYListByTableAsY_Double(int y) {

		return getDoubleListByY(y);
	}

	private List<Double> getDoubleListByY(int yIndex) {

		List<Double> doubleList = new ArrayList<Double>();

		for (int i = 0; i < tableData.size(); i++) {
			List<String> line = tableData.get(i);

			if (line.size() > yIndex) {
				String point = line.get(yIndex);
				// 如果项为空，或者为指定的填充字符，则使用 0 代替
				if (line.equals("")
						|| StationFinalFields.No_Data_Point.equals(line)) {
					doubleList.add(0d);
				} else {
					try {
						doubleList.add(Double.parseDouble(point));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		return doubleList;
	}

}
